package com.swg.common;

import lombok.Getter;
import org.codehaus.jackson.annotate.JsonIgnore;
import org.codehaus.jackson.map.annotate.JsonSerialize;

import java.io.Serializable;

/**
 * @Author 【swg】.
 * @Date 2018/1/2 20:42
 * @DESC
 * @CONTACT 317758022@qq.com
 */
@Getter
//json序列化时，null的对象,key会消失
@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
public class ServerResponse<T> implements Serializable{
    private static final long serialVersionUID = -6819559706322722855L;

    private int status;
    private String msg;
    private T data;

    private ServerResponse(int status){
        this.status = status;
    }
    private ServerResponse(int status,T data){
        this.status = status;
        this.data = data;
    }
    private ServerResponse(int status,String msg,T data){
        this.status = status;
        this.msg = msg;
        this.data = data;
    }
    private ServerResponse(int status,String msg){
        this.status = status;
        this.msg = msg;
    }

    //判断是否成功
    @JsonIgnore
    public boolean isSuccess(){
        return this.status == ResponseEnum.SUCCESS.getCode();
    }

    /**
     * 返回成功的几个方法
     * @param <T>
     * @return
     */
    public static <T>ServerResponse<T> createBySuccess(){
        return new ServerResponse<>(ResponseEnum.SUCCESS.getCode());
    }

    public static <T>ServerResponse<T> createBySuccessMessage(String msg){
        return new ServerResponse<>(ResponseEnum.SUCCESS.getCode(),msg);
    }

    public static <T>ServerResponse<T> createBySuccess(T data){
        return new ServerResponse<>(ResponseEnum.SUCCESS.getCode(),data);
    }

    public static <T>ServerResponse<T> createBySuccess(String msg,T data){
        return new ServerResponse<>(ResponseEnum.SUCCESS.getCode(),msg,data);
    }


    /**
     * 返回失败的几个方法
     * @param <T>
     * @return
     */
    public static <T>ServerResponse<T> createByError(){
        return new ServerResponse<>(ResponseEnum.ERROR.getCode(),ResponseEnum.ERROR.getDesc());
    }

    public static <T>ServerResponse<T> createByError(T data){
        return new ServerResponse<>(ResponseEnum.ERROR.getCode(),data);
    }

    public static <T>ServerResponse<T> createByErrorMessage(String msg){
        return new ServerResponse<>(ResponseEnum.ERROR.getCode(),msg);
    }

    public static <T>ServerResponse<T> createByErrorCodeMessage(int code,String msg){
        return new ServerResponse<>(code,msg);
    }




}
